#coding=utf-8

'''
Created on 2011-8-30

@author: chris
'''

import pymongo #@UnresolvedImport
from pymongo import Connection #@UnresolvedImport

class __StorageClass(object):
    '''
            存储模块
    '''

    def __init__(self):
        # 初始化数据库
#        self.connection = Connection('oni', 9190)
        self.connection = Connection('localhost', 27017)
        self.db = self.connection['harvester']
   
    # 条件查询
    def query(self, collectionName, cond={}, sort=None, start=None, limit=None, fields={}):
        result = None
        if sort == None:
            if start == None and limit == None:
                result = self.db[collectionName].find(fields, cond)
            elif start == None and limit != None:
                result = self.db[collectionName].find(fields, cond).limit(limit)
            elif start != None and limit == None:
                result = self.db[collectionName].find(fields, cond).skip(start)
            elif start != None and limit != None:
                result = self.db[collectionName].find(fields, cond).skip(start).limit(limit)
        else:
            if start == None and limit == None:
                result = self.db[collectionName].find(fields, cond).sort(sort)
            elif start == None and limit != None:
                result = self.db[collectionName].find(fields, cond).sort(sort).limit(limit)
            elif start != None and limit == None:
                result = self.db[collectionName].find(fields, cond).sort(sort).skip(start)
            elif start != None and limit != None:
                result = self.db[collectionName].find(fields, cond).sort(sort).skip(start).limit(limit)
        self.connection.end_request() # 回到连接池
        return result
    
    # 查询一条记录
    def query_one(self, collectionName, cond):
        result = self.db[collectionName].find_one(cond)
        self.connection.end_request() # 回到连接池
        return result
    
    # 保存item的数据
    # itemData : json格式
    def save_item_data(self, collectionName, itemData):
        obj = self.db[collectionName].save(itemData)
        self.connection.end_request() # 回到连接池
        return obj
    
print '[info] Connecting to database....'
db = __StorageClass()
print '[info] Database connected'
           
